package com.nwpu.hass.interceptor;

import antlr.Token;
import com.nwpu.hass.exceptions.AuthorizeException;
import com.nwpu.hass.service.RedisService;
import com.nwpu.hass.utils.Code;
import com.nwpu.hass.utils.MyResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 第一步拦截，在redis中做验证
 * 验证通过的话，传给逻辑层进行权限验证
 * 验证不通过的话，将返回给前端一个failure，并在其中内嵌一个URL指向认证中心。
 *
 * @author : Qin
 * @date : 2021-01-07 10:59
 **/
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        log.info(path);
        String token;
        //不对注册接口进行拦截，并在注册完成之后，签发一个jwt
        // toDo 拦截路径重新配置
        if (path.matches("/user/register") || path.matches("/user/login")
        || path.matches("/device/checkIn") || path.matches("/user/face/.*")) {
            log.info("requestUrl: {}", path);
            return true;
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            token = request.getHeader("token");
            log.info("token is " + token);

            if(!redisService.verifyToken(token)){
                throw new AuthorizeException(token);
            }
        }
        log.info(redisService.getUserId(token).toString());

        return true;
    }
}
